import { ExecutionStep, ExecutionTrace } from '@/types';
import { format } from 'date-fns';

// 格式化时间戳
export function formatTimestamp(timestamp: string): string {
  try {
    return format(new Date(timestamp), 'yyyy-MM-dd HH:mm:ss');
  } catch {
    return timestamp;
  }
}

// 计算步骤耗时
export function calculateStepDuration(steps: ExecutionStep[]): ExecutionStep[] {
  return steps.map((step, index) => {
    if (index === 0) {
      return { ...step, duration: 0 };
    }
    
    const prevStep = steps[index - 1];
    const currentTime = new Date(step.timestamp).getTime();
    const prevTime = new Date(prevStep.timestamp).getTime();
    const duration = currentTime - prevTime;
    
    return { ...step, duration };
  });
}

// 按时间排序步骤
export function sortStepsByTime(steps: ExecutionStep[]): ExecutionStep[] {
  return [...steps].sort((a, b) => 
    new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  );
}

// 提取关键信息
export function extractKeyInfo(trace: ExecutionTrace) {
  const totalSteps = trace.steps.length;
  const totalTools = trace.steps.reduce((acc, step) => 
    acc + (step.usedTools?.length || 0), 0
  );
  const totalDocuments = trace.steps.reduce((acc, step) => 
    acc + (step.sourceDocuments?.length || 0), 0
  );
  
  const firstStep = trace.steps[0];
  const lastStep = trace.steps[trace.steps.length - 1];
  
  const totalDuration = firstStep && lastStep 
    ? new Date(lastStep.timestamp).getTime() - new Date(firstStep.timestamp).getTime()
    : 0;

  return {
    totalSteps,
    totalTools,
    totalDocuments,
    totalDuration,
    startTime: firstStep?.timestamp,
    endTime: lastStep?.timestamp,
  };
}

// 搜索步骤内容
export function searchSteps(steps: ExecutionStep[], query: string): ExecutionStep[] {
  if (!query.trim()) return steps;
  
  const lowerQuery = query.toLowerCase();
  return steps.filter(step => 
    step.input.toLowerCase().includes(lowerQuery) ||
    step.output.toLowerCase().includes(lowerQuery) ||
    step.nodeName.toLowerCase().includes(lowerQuery) ||
    step.agentName.toLowerCase().includes(lowerQuery)
  );
}
